//
//  ContactViewController.mm
//  cocoa-jabber-messenger
//
//  Created by Sangeun Kim on 4/17/11.
//  Copyright 2011 NHN Corporation. All rights reserved.
//

#import "ContactViewController.h"
#import "BuddyCell.h"
#import "XMPP.h"
#import "ContactItem.h"
#import "ContactManager.h"
#import "ContactDataContext.h"

#pragma mark *** ContactViewController ***

@implementation ContactViewController


#pragma mark *** Initialize ***
- (void) awakeFromNib
{
	iGroupRowCell = [[NSTextFieldCell alloc] init];
	[iGroupRowCell setEditable:NO];
	[iGroupRowCell setLineBreakMode:NSLineBreakByTruncatingTail];
    
    [xmpp registerConnectionDelegate:self];
    [xmpp setRosterDelegate:self];
    
    groupManager = [[ContactGroupManager alloc]init];
    
    [contactList setIntercellSpacing:NSMakeSize(0,0)];
    [contactList setTarget:self];
    [contactList setDoubleAction:@selector(onDoubleClick:)];
    [contactList setAction:@selector(onClick:)];
    //    [contactList setDataSource:self];
    
}

- (void)dealloc
{
    [groupManager release];
    [iGroupRowCell release];
    [super dealloc];
}

- (void) onClick:(id)sender
{
    NSInteger selected = [contactList selectedRow];
    NSTreeNode* node = [contactList itemAtRow:selected];
    if ([contactList isExpandable:node]) {
        if ([contactList isItemExpanded:node]) {
            [contactList collapseItem:node];
        }
        else {
            [contactList expandItem:node];
        }
    }    
}

- (void) onDoubleClick:(id)sender
{
    NSInteger selected = [contactList selectedRow];
    NSTreeNode* node = [contactList itemAtRow:selected];
    NSManagedObject* object = [node representedObject];
    NSString* jid = [object valueForKey:@"jid"];
    if (!jid) {
        return;
    }
    if (![jid length]) {
        return;
    }
    
    [xmpp startChat:jid];
    
}

#pragma mark -


#pragma mark *** XMPP Delegate ***

- (void) onConnect
{
    [[self view]setHidden:NO];
    NSUInteger style = [[[self view]window]styleMask]; 
    [[[self view]window]setStyleMask:style|NSResizableWindowMask ];
}

- (void) onDisconnectWithErrorCode:(NSInteger) errorCode
{
    [[self view]setHidden:YES];
}

- (void) onRoster:(ContactItem*) item;
{
    NSString* presentedGroupName = nil;
    NSString* groupName = nil;
    if ([item groups]) {
        if ([[item groups]count])
        {
            groupName = [[item groups]objectAtIndex:0];
            if ([item presence] == 5) {
                presentedGroupName = OFFLINE_GROUP_NAME;
            }
            else if ([item presence] != -1) {
                presentedGroupName = groupName;
            }
        }
    }
    
    if (!presentedGroupName) {
//        NSInteger count = [contactDataContext contactCountInGroup:groupName];
        presentedGroupName = [contactDataContext groupNameByContact:item];
    }
    NSInteger count = [contactDataContext contactCountInGroup:presentedGroupName];
    [contactDataContext updateContact:item intoGroup:groupName];
    if (!count) {
        [contactList expandItem:nil expandChildren:YES];
    }
}


#pragma mark -
#pragma mark *** outlineView dataset ***

- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item
{
/*	if (item == nil) {
		return [[groupManager groups ]objectAtIndex:index];
	}
    
    if ([item isKindOfClass:[ContactGroup class]]) {
        return [[item contacts]objectAtIndex:index];
    }*/    
    return nil;
    
}

- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item
{
/*    if ([item isKindOfClass:[ContactGroup class]]) {
        return YES;
    }*/
	return NO;    
}

- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item
{
/*	if (item == nil) {
		return [[groupManager groups] count];
	}
	
    if ([item isKindOfClass:[ContactGroup class]]) {
        return [[item contacts]count];
    }
  */  
	return 0;
	
}

#include "gloox/presence.h"
- (NSString*) statusString:(NSInteger)presence
{
    switch ( presence ) {
        case gloox::Presence::Available:
            return [NSString stringWithString:@"Available"];
            break;
            
        case gloox::Presence::Chat:
            return [NSString stringWithString:@"Chat"];
            break;
            
        case gloox::Presence::Away:
            return [NSString stringWithString:@"Away"];
            break;
            
        case gloox::Presence::DND:
            return [NSString stringWithString:@"Do Not Disturb"];
            break;
            
        case gloox::Presence::XA:
            return [NSString stringWithString:@"Away for an extended period of time"];
            break;
            
        case gloox::Presence::Unavailable:
            return [NSString stringWithString:@"Unavailable"];
            break;
            
        case gloox::Presence::Probe:
            return [NSString stringWithString:@"Probe"];
            break;
            
        case gloox::Presence::Error:
            return [NSString stringWithString:@"Error"];
            break;   
        case PRESENCE_UNKNOWN:
            return [NSString stringWithString:@"Offline - NOTUSED"];
            break;    
        default:
            return [NSString stringWithString:@"Unknown"];
            break;
    }
    
}

- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
{
    BOOL group = ![[item parentNode]parentNode];
    NSManagedObject* obj = [item representedObject];
    
    if (group) {
        NSString* name = [NSString stringWithFormat:@"\t%@", [obj valueForKey:@"name"]];
        return name;
    }
    
    if ([[tableColumn identifier] isEqualToString:@"image"]) {
        NSData* imageData = [obj valueForKey:@"image"];
        if (imageData) {
            NSImage* image = [[[NSImage alloc] initWithData:imageData]autorelease];
            return image;
        }
        return [NSImage imageNamed:@"NSUser"];
    }
    if ([[tableColumn identifier] isEqualToString:@"name"]) {
        NSString* status = [obj valueForKey:@"status"];
        if (![status length]) {
            status = [self statusString:[[obj valueForKey:@"presence"] integerValue]];
        }
        NSString* name = [NSString stringWithFormat:@"%@ - %@", [obj valueForKey:@"name"], status];
        [(BuddyCell*)[tableColumn dataCell] setSubTitle:[obj valueForKey:@"jid"]];
        [(BuddyCell*)[tableColumn dataCell] setTitle:name];
        
        return name;
    }
    
    return nil;
    
}

- (NSCell *)outlineView:(NSOutlineView *)outlineView dataCellForTableColumn:(NSTableColumn *)tableColumn item:(id)item
{
    if (tableColumn == nil) {
        return [[item parentNode]parentNode]?nil:iGroupRowCell;
	}
	return nil;
}

- (BOOL)outlineView:(NSOutlineView *)outlineView isGroupItem:(id)item {
    return [[item parentNode]parentNode]?NO:YES;
}

- (CGFloat)outlineView:(NSOutlineView *)outlineView heightOfRowByItem:(id)item
{
    return [[item parentNode]parentNode]?[contactList rowHeight]:20;
}
#pragma mark -


@end
